package com.xianye.erp.service.product.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import com.xianye.erp.factory.ApiFacade;
import com.xianye.erp.service.product.ProductManager;
import com.xianye.erp.util.PageData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;


@Service("productAPI")
public class ProductAPI {
	protected Logger log = Logger.getLogger(this.getClass());
	@Resource(name = "productService")
	private ProductManager productService;

	@Autowired
	private JdbcTemplate jdbc;

	@Autowired
	private ApiFacade facade;

	private List<PageData> productList = new ArrayList<>();
	private List<PageData> updateProductList = new ArrayList<>();
	private List<PageData> imgList = new ArrayList<>();
	private List<PageData> skuList = new ArrayList<>();
	private List<PageData> skupropertyList = new ArrayList<>();
	private List<PageData> productPropertyList = new ArrayList<>();
	private List<String> productImgDel = new ArrayList<>();
	private List<String> skuDel = new ArrayList<>();
	private List<String> skupropertyDel = new ArrayList<>();
	private List<String> productPropertyDel = new ArrayList<>();
	public ProductAPI(){
		
	}
	/**
	 * 从redis读取数据插入数据库
	 */
	public void saveProduct(List<JSONObject> list){

		String sql = "SELECT productId from e_product  ";
		HashMap<String, String> map = new HashMap<>();
		SqlRowSet set = jdbc.queryForRowSet(sql);
		while(set.next()){
			map.put(set.getString("productId"), set.getString("productId"));
		}
		try {
			for(int i=0;i<list.size();i++){

				JSONObject listDetail = list.get(i);
				if(listDetail!=null && listDetail.containsKey("product_id")){
					if(map.containsKey(listDetail.get("product_id")+"")){
						edit(listDetail.getJSONObject("detail"), listDetail);
					}else{
						save(listDetail.getJSONObject("detail"), listDetail);
					}
				}
				//System.out.println("listDetail:"+listDetail);

			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("产品数据从redis读取到mysql异常", e);
		}
		batchExucte();
	}
	
	public void  batchExucte(){
		try {			
			/**------------删除--------------**/
			System.out.println("productImgDel:"+productImgDel.size());
			if(productImgDel.size()>0){
				productService.batchDelete_img(productImgDel);
				productImgDel.clear();
			}
			System.out.println("skuDel:"+skuDel.size());
			if(skuDel.size()>0){
				productService.batchDelete_sku(skuDel);
				skuDel.clear();
			}
			System.out.println("skupropertyDel:"+skupropertyDel.size());
			if(skupropertyDel.size()>0){
				productService.batchDelete_sku_property(skupropertyDel);
				skupropertyDel.clear();
			}
			System.out.println("productPropertyDel:"+productPropertyDel.size());
			if(productPropertyDel.size()>0){
				productService.batchDelete_property(productPropertyDel);
				productPropertyDel.clear();
			}
			
			/**---------------添加-----------------**/
			
		
			System.out.println("productList:"+productList.size());
			if(productList.size()>0){
				productService.batchSave(productList);
				productList.clear();
			}
			System.out.println("productPropertyList:"+productPropertyList.size());
			if(productPropertyList.size()>0){
				productService.batchSave_property(productPropertyList);
				productPropertyList.clear();
			}
			System.out.println("productPropertyList:"+productPropertyList.size());
			System.out.println("imgList:"+imgList.size());
			if(imgList.size()>0){
				productService.batchSave_img(imgList);
				imgList.clear();
			}
			System.out.println("imgList:"+imgList.size());
			System.out.println("skuList:"+skuList.size());
			if(skuList.size()>0){
				productService.batchSave_sku(skuList);
				skuList.clear();
			}
			System.out.println("skupropertyList:"+skupropertyList.size());
			if(skupropertyList.size()>0){
				productService.batchSave_sku_property(skupropertyList);
				skupropertyList.clear();
			}
			
			System.out.println("updateProductList:"+updateProductList.size());
			/**------------更新------------**/
			if(updateProductList.size()>0){
				productService.batchUpdate(updateProductList);
				updateProductList.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			productList.clear();
			updateProductList.clear();
		}		
	}
	public void edit(JSONObject json,JSONObject listDetail) {
		try {
		
		PageData p = new PageData();
		p.put("productId", json.get("product_id"));
		PageData pd = productService.findByProductId(p);
		pd.put("subject", json.get("subject"));
		pd.put("detail", json.get("detail"));
		pd.put("deliveryTime", json.get("delivery_time"));
		pd.put("ownerMemberId", json.get("owner_member_id"));
		pd.put("ownerMemberSeq", json.get("owner_member_seq"));
		pd.put("categoryId", json.get("category_id"));
		pd.put("packageType", json.get("package_type")==null?"":json.get("package_type"));
		pd.put("packageLength", json.get("package_length"));
		pd.put("packageWidth", json.get("package_width"));
		pd.put("packageHeight", json.get("package_height"));
		pd.put("grossWeight", json.get("gross_weight"));
		pd.put("isPackSell", json.get("is_pack_sell"));
		pd.put("reduceStrategy", json.get("reduce_strategy"));
		pd.put("bulkDiscount", json.get("bulk_discount"));
		pd.put("productUnit", json.get("product_unit"));
		pd.put("wsValidNum", json.get("ws_valid_num"));
		//pd.put("wsOfflineDate", DateUtil.parse(json.get("wsOfflineDate")+""));
		pd.put("wsDisplay", json.get("ws_display"));
		pd.put("productStatusType", json.get("product_status_type"));
		pd.put("currencyCode", json.get("currency_code"));
		pd.put("freightTemplateId", json.get("freight_template_id"));
		pd.put("baseUnit", json.get("base_unit"));
		pd.put("bulkOrder", json.get("bulk_order"));
		pd.put("groupId", json.get("group_id"));
		pd.put("isImageDynamic", json.get("is_image_dynamic"));
		pd.put("productPrice", json.get("product_price"));
		pd.put("promiseTemplateId", json.get("promise_template_id"));
		pd.put("sizechartId", json.get("sizechart_id"));
		pd.put("MODIFY_DATE", new Date());
		pd.put("imageURLs", json.getString("image_u_r_ls"));
		pd.put("productMaxPrice", listDetail.get("product_max_price"));
		pd.put("productMinPrice", listDetail.get("product_min_price"));
		updateProductList.add(pd);
		//保存图片
		productImgDel.add(json.get("product_id")+"");
		String ProductImage = "";
		ProductImage = saveImage(json);
		//保存类目属性
		productPropertyDel.add(json.get("product_id")+"");
		if(json.containsKey("aeop_ae_product_propertys")){
			saveProductPropertys(json);
		}
		//保存sku
		skuDel.add(json.get("product_id")+"");
		skupropertyDel.add(json.get("product_id")+"");
		if(json.containsKey("aeop_ae_product_s_k_us")){
			saveSku(json,ProductImage);
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String saveImage(JSONObject json){
		try{
			String ProductImage = "";
			String [] imgs = json.getString("image_u_r_ls").split(";");
			for(int i=0;i<imgs.length;i++){
				if(i==0){
					ProductImage = imgs[i];
				}
				PageData img = new PageData();
				img.put("productId", json.get("product_id"));
				img.put("image_url", imgs[i]);
				img.put("CREATE_DATE", new Date());
				productService.save_img(img);
				imgList.add(img);
			}
			return ProductImage;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}
	public void saveProductPropertys(JSONObject json){
		try{
			JSONObject res = json.getJSONObject("aeop_ae_product_propertys");
			if(res.containsKey("aeop_ae_product_property")){
				JSONArray aeopAeProductPropertys = res.getJSONArray("aeop_ae_product_property");
				if(aeopAeProductPropertys!=null && !aeopAeProductPropertys.isEmpty()&&aeopAeProductPropertys.toString().length()>2 ){
					for(int i=0;i<aeopAeProductPropertys.size();i++){
						JSONObject obj = aeopAeProductPropertys.getJSONObject(i);
						PageData pro = new PageData();
						pro.put("productId", json.get("product_id"));
						pro.put("attrNameId", obj.get("attr_name_id"));
						pro.put("attrName", obj.get("attr_name"));
						pro.put("attrValueId", obj.get("attr_value_id"));
						pro.put("attrValue", obj.get("attr_value"));
						pro.put("CREATE_DATE", new Date());
						productPropertyList.add(pro);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void saveSku(JSONObject json,String ProductImage){
		//System.out.println(json.toString());
		JSONObject res = json.getJSONObject("aeop_ae_product_s_k_us");
		if(res.containsKey("aeop_ae_product_sku")){
			JSONArray skus = res.getJSONArray("aeop_ae_product_sku");
			for(int i=0;i<skus.size();i++){
				JSONObject obj = skus.getJSONObject(i);
				PageData sku = new PageData();
				sku.put("productId", json.get("product_id")==null?"":json.get("product_id"));
				sku.put("skuPrice", obj.get("sku_price"));
				if(obj.get("id").toString().equals("<none>")){
					sku.put("skuCode", json.get("product_id")==null?"":json.get("product_id"));
				}else{
					sku.put("skuCode", json.get("product_id")==null?"":json.get("product_id")+"-"+obj.get("id"));
				}

				sku.put("skuStock", obj.get("sku_stock")==null?"":obj.get("sku_stock"));
				sku.put("ipmSkuStock", obj.get("ipm_sku_stock")==null?"":obj.get("ipm_sku_stock"));
				sku.put("skuId", obj.get("id")==null?"":obj.get("id"));
				JSONObject ress = obj.getJSONObject("aeop_s_k_u_property_list");
				if(ress.containsKey("aeop_sku_property")){
					JSONArray array = ress.getJSONArray("aeop_sku_property");
					String skuImage = "";
					for(int j=0;j<array.size();j++){
						JSONObject spro = array.getJSONObject(j);
						PageData pro = new PageData();
						if(spro.get("sku_image")!=null){
							skuImage = spro.getString("sku_image");
						}
						pro.put("productId", json.get("product_id"));
						pro.put("skuId", obj.get("id"));
						pro.put("skuPropertyId", spro.get("sku_property_id"));
						pro.put("propertyValueId", spro.get("property_value_id"));
						pro.put("propertyValueDefinitionName", spro.get("property_value_definition_name"));
						pro.put("skuImage", spro.get("sku_image"));
						pro.put("CREATE_DATE", new Date());
						skupropertyList.add(pro);
					}

					if(skus.size()==1){
						sku.put("imageURL", ProductImage);
					}else{
						if(skuImage.length()==0){
							sku.put("imageURL", ProductImage);
						}else{
							sku.put("imageURL", skuImage);
						}
					}

				}
				if(sku.get("imageURL")==null){
					sku.put("imageURL", "");
				}
				sku.put("STORE_ID",json.get("STORE_ID")==null?"":json.get("STORE_ID"));
				sku.put("skuNameEN", json.get("subject")==null?"":json.get("subject"));
				sku.put("skuNameCN", json.get("subject")==null?"":json.get("subject"));
				sku.put("currencyCode", obj.get("currencyCode")==null?"":obj.get("currencyCode"));
				sku.put("CREATE_DATE", new Date());
				//log.info("sku----------------------"+sku);
				skuList.add(sku);
			}
		}

	}
	public void save(JSONObject json,JSONObject listDetail) throws Exception {
		try {		
		PageData pd = new PageData();
		pd.put("productId", json.get("product_id")==null?"":json.get("product_id"));
		pd.put("subject", json.get("subject")==null?"":json.get("subject"));
		pd.put("detail", json.get("detail")==null?"":json.get("detail"));
		pd.put("deliveryTime", json.get("delivery_time")==null?0:json.get("delivery_time"));
		pd.put("ownerMemberId", json.get("owner_member_id")==null?"":json.get("owner_member_id"));
		pd.put("ownerMemberSeq", json.get("owner_member_seq")==null?0:json.get("owner_member_seq"));
		pd.put("categoryId", json.get("category_id")==null?0:json.get("category_id"));
		pd.put("packageType", json.get("package_type")==null?"":json.get("package_type"));
		pd.put("packageLength", json.get("package_length")==null?0:json.get("package_length"));
		pd.put("packageWidth", json.get("package_width")==null?0:json.get("package_width"));
		pd.put("packageHeight", json.get("package_height")==null?0:json.get("package_height"));
		pd.put("grossWeight", json.get("gross_weight")==null?0:json.get("gross_weight"));
		pd.put("isPackSell", json.get("is_pack_sell")==null?"":json.get("is_pack_sell"));
		pd.put("reduceStrategy", json.get("reduce_strategy")==null?"":json.get("reduce_strategy"));
		pd.put("bulkDiscount", json.get("bulk_discount")==null?"":json.get("bulk_discount"));
		pd.put("productUnit", json.get("product_unit")==null?0:json.get("product_unit"));
		pd.put("wsValidNum", json.get("ws_valid_num")==null?0:json.get("ws_valid_num"));
		pd.put("wsOfflineDate","");
		pd.put("wsDisplay", json.get("ws_display")==null?"":json.get("ws_display"));
		pd.put("productStatusType", json.get("product_status_type")==null?"":json.get("product_status_type"));
		pd.put("currencyCode", json.get("currency_code")==null?"":json.get("currency_code"));
		pd.put("freightTemplateId", json.get("freight_template_id")==null?"":json.get("freight_template_id"));
		pd.put("baseUnit", json.get("base_unit")==null?"0":json.get("base_unit"));
		pd.put("bulkOrder", json.get("bulk_order")==null?"0":json.get("bulk_order"));
		pd.put("groupId", json.get("group_id")==null?"0":json.get("group_id"));
		pd.put("isImageDynamic", json.get("is_image_dynamic")==null?"":json.get("is_image_dynamic"));
		pd.put("productPrice", json.get("product_price")==null?"":json.get("product_price"));
		pd.put("promiseTemplateId", json.get("promise_template_id")==null?"":json.get("promise_template_id"));
		pd.put("sizechartId", json.get("sizechart_id")==null?"":json.get("sizechart_id"));
		pd.put("STORE_ID", json.get("STORE_ID"));
		pd.put("CREATE_DATE", new Date());
		pd.put("MODIFY_DATE", new Date());
		pd.put("CREATE_USER_NAME", "SYSTEM");
		pd.put("imageURLs", json.getString("image_u_r_ls")==null?"":json.getString("image_u_r_ls"));
		pd.put("productMaxPrice", listDetail.get("product_max_price")==null?"":listDetail.getString("product_max_price"));
		pd.put("productMinPrice", listDetail.get("product_min_price")==null?"":listDetail.getString("product_min_price"));
		//log.error(pd.toString());
		productList.add(pd);
		//保存图片
		String ProductImage = "";
		ProductImage = saveImage(json);
		//保存类目属性
		if(json.containsKey("aeop_ae_product_propertys")){
			saveProductPropertys(json);
		}
		//保存sku
		if(json.containsKey("aeop_ae_product_s_k_us")){
			saveSku(json,ProductImage);
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	

}
